package com.blast.manager.delay.presenter

import android.text.TextUtils
import com.blast.manager.delay.DelayActivity
import com.blast.manager.delay.event.KeyDownEvent
import com.wxl.common.AppContext
import com.wxl.common.life.LifecycleManager
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.serialport.*
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.Toll
import com.wxl.common.wiget.ProgressUpdatePop


/**
 * 处理串口数据
 */
class DelayCjqPortPresenter : AbsDelayPresenter() {

    var mCurrentDetonatorNum = 0//当前雷管数

    var mDetonatorTotalNum = 0//采集器里的雷管总数

    var mDetonatorMaxNumLimit = 0 //最大可组网数

    var mCollectorId = ""//采集器编号

    val mKeyDownEvent = KeyDownEvent()

    private var mProgressUpdatePop:ProgressUpdatePop?=null

    override fun onDelayCreated(vararg args: Any) {

        mDetonatorMaxNumLimit = AppContext.appContext.getLeiGuanMaxNum()

        /**
         * 检查采集器升级
         */
        CJQUpdateModel.checkCjq(object : CJQUpdateModel.Companion.OnCjqUpCallback {

            override fun onCjqUpEnd() {
                receiveCjqData()
            }

            override fun onCiqUpStart() {
                mKeyDownEvent.isCanBack = false
                LifecycleManager.manager.refreshLiveData(mKeyDownEvent)
            }

        })

    }


    /**
     * 接收采集器基本信息
     */
    private fun receiveCjqData() {

        SerialD.registerCjqSerial(object : Serial() {
            //正常插入采集器返回
            override fun loadReceiveData(data: String) {
                (context as DelayActivity).addLog("采集器","检测到采集器插入")
                SerialPortManager.send(CmdCode.CJQ_READ_INFO_CMD)//发送获取采集器信息命令
            }
        })

        Serials.registerSingleStartHexSerial(CmdCode.CJQ_READ_INFO_ASK, object : Serial() {
            //获得采集器信息返回
            override fun loadReceiveData(data: String) {
                if (!TextUtils.isEmpty(data) && data.length > 31) {
                    (context as DelayActivity).addLog("采集器","获得采集器信息")
                    parseCjqData(data)
                }
            }
        })

        Serials.registerSingleStartHexSerial(CmdCode.CJQ_UP_BLOCK_ASK,object : Serial(){
            override fun loadReceiveData(data: String) {
                receiveCjqData()//重新注册采集器接收
                updateImportProgress(-1,"采集器已拔出...")
                mKeyDownEvent.isCanBack = true
                LifecycleManager.manager.refreshLiveData(mKeyDownEvent)
            }
        })

        SerialPortManager.startQueryPortWork()
    }

    /**
     * 解析采集器基本信息
     */
    private fun parseCjqData(data: String) {
        mCollectorId = data.substring(16, 28)
        mCurrentDetonatorNum = 0
        mDetonatorTotalNum = 0
        AppContext.appContext.matchCjq(mCollectorId,
            object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
                override fun onNext(t: Boolean) {
                    if (t) {
                        mDetonatorTotalNum = Integer.valueOf(data.substring(12, 16), 16)
                        mProgressUpdatePop = ProgressUpdatePop.show(context)
                        updateImportProgress(mCurrentDetonatorNum, "正在导入延时方案(${mCurrentDetonatorNum}/$mDetonatorMaxNumLimit)...")
                        importDelayPlanData()
                    }
                }
            })

        Serials.registerStartHexSerial(CmdCode.LEI_GUAN_CJQ_INFO_OK_ASK, object : Serial() {
            //获得采集器雷管信息
            override fun loadReceiveData(data: String) {
                if (!TextUtils.isEmpty(data) && data.length > 40) {
                    mCurrentDetonatorNum++
                    updateImportProgress(mCurrentDetonatorNum, "正在导入延时方案(${mCurrentDetonatorNum}/$mDetonatorMaxNumLimit)...")
                    parseDetonatorData(data)
                    importDelayPlanData()
                }
            }
        })
    }


    /**
     * 更新导入进度
     */
    private fun updateImportProgress(p: Int, sub: String) {
        if(mProgressUpdatePop == null && !mProgressUpdatePop!!.isShow){
            return
        }
        val max =
            if (mDetonatorTotalNum > mDetonatorMaxNumLimit) mDetonatorMaxNumLimit else mDetonatorTotalNum
        ProgressUpdatePop.updateProgress(mProgressUpdatePop!!,if(p>0) p/2 else p, sub, "导入延时方案", max+2)
    }


    /**
     * 导入延时方案
     */
    private fun importDelayPlanData() {
        if (mCurrentDetonatorNum < mDetonatorTotalNum && mCurrentDetonatorNum < mDetonatorMaxNumLimit) {
            val num = SerialUtil.getCurrentDetonatorNum(mCurrentDetonatorNum)
            SerialPortManager.send(CmdCode.LEI_GUAN_CJQ_INFO_CMD + num)
        } else {
            if(mCurrentDetonatorNum >= mDetonatorMaxNumLimit){
                Toll.toll("已达到当前设置的最大组网雷管数。")
            }
            getPresenter(ShowDelayDataPresenter::class.java).refreshData()
            updateImportProgress(mCurrentDetonatorNum, "正在保存延时方案...")
            getPresenter(ShowDelayDataPresenter::class.java).saveDataToDb(object : ObservableUtil.Companion.OnNextCallback<Boolean>(){
                override fun onNext(t: Boolean) {
                    //val max = if (mDetonatorTotalNum > mDetonatorMaxNumLimit) mDetonatorMaxNumLimit else mDetonatorTotalNum
                    updateImportProgress(-1, "正在保存延时方案...")
                    getPresenter(ShowDelayDataPresenter::class.java).delayShowImportDataPop(mDetonatorTotalNum)
                    mKeyDownEvent.isCanBack = true
                    LifecycleManager.manager.refreshLiveData(mKeyDownEvent)
                }
            })
        }
    }



    /**
     * 解析雷管信息
     */
    private fun parseDetonatorData(data: String) {
        val mLeiGuanEntity = LeiGuanEntity.parseDetonator(data)
        mLeiGuanEntity.collectorNumber = mCollectorId
        getPresenter(ShowDelayDataPresenter::class.java).checkLeiGuanRepeat(mLeiGuanEntity)
    }

    override fun onDestroy() {
        super.onDestroy()
        Serials.unRegisterStartHexSerial(CmdCode.LEI_GUAN_CJQ_INFO_OK_ASK)
        Serials.unRegisterSingleStartHexSerial(CmdCode.CJQ_READ_INFO_ASK)
        SerialD.unRegisterCjqSerial()
        Serials.unRegisterSingleStartHexSerial(CmdCode.CJQ_UP_BLOCK_ASK)
    }
}